<?php
/**
 * 客户端
 */

namespace app\http\Controllers\Manage;

use think\App;
use think\Request;
use app\models\common\ClientsModel;

class ClientsController extends BaseController
{

    private $model;

    public function __construct(App $app, Request $request)
    {
        parent::__construct($app, $request);
        $this->model = new ClientsModel();
    }


    /**
     * 列表页面
     * @return void
     */
    public function index()
    {
        $data = [];
        return $this->view('clients/list', $data);
    }

    /**
     * 记录列表
     * @param Request $request
     * @return void
     */
    public function getRecordList(Request $request)
    {
        $param = $request->param();
        $page = isset($param['page']) ? intval($param['page']) : 1;
        $limit = isset($param['limit']) ? intval($param['limit']) : 1;
        $count = $this->model->getRecordCount($param);
        $parger = turnPageToStartEnd($page, $limit);
        $list = $this->model->getRecordList($param, $parger['start'], $parger['limit']);
        return apiResponse(STATUS_CODE_SUCCESS, 'success', formatPager($count, $list, $page, $limit));
    }


    /**
     * 编辑页面
     * @param $id
     * @param Request $request
     * @return void
     */
    public function edit($id, Request $request)
    {
        $data = [
            'id' => $id,
            'info' => [],
        ];
        if ($id > 0) {
            $info = $this->model->getInfoById($id);
            if (!$info) return $this->showErrorPage(STATUS_CODE_NOTFOUND, '记录不存在');
            $data['info'] = $info;
        }
        return $this->view('clients/edit', $data);
    }


    /**
     * 添加
     * @param Request $request
     * @return void
     */
    public function createRecord(Request $request)
    {
        $params = $request->param();
        $res = $this->model->createRecord($params);
        if ($res['status'] != STATUS_CODE_SUCCESS) {
            return apiResponse($res['status'], $res['msg']);
        }
        return apiResponse(STATUS_CODE_SUCCESS, '保存成功');
    }


    /**
     * 修改
     * @param $id
     * @param Request $request
     * @return void
     */
    public function updateRecord($id, Request $request)
    {
        $params = $request->param();
        $res = $this->model->updateRecord($id, $params);
        if ($res['status'] != STATUS_CODE_SUCCESS) {
            return apiResponse($res['status'], $res['msg']);
        }
        return apiResponse(STATUS_CODE_SUCCESS, '修改成功');
    }

    /**
     * 删除
     * @param $id
     * @param Request $request
     * @return void
     */
    public function deleteRecord($id, Request $request)
    {
        $res = $this->model->deleteRecord($id);
        if ($res['status'] != STATUS_CODE_SUCCESS) {
            return apiResponse($res['status'], $res['msg']);
        }
        return apiResponse(STATUS_CODE_SUCCESS, 'success');
    }

}